package com.lx.huimailf.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


import com.lx.huimailf.MyApplication;
import com.lx.huimailf.R;
import com.lx.huimailf.fragment.BackGoodsFragment;
import com.lx.huimailf.fragment.OrderFragment;
import com.lx.huimailf.fragment.UserFragment;
import com.lx.huimailf.update.DownAPKService;
import com.lx.huimailf.utils.Tools;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.Call;


public class MainFragmentActivity extends FragmentActivity {
	private ViewPager viewPager;
	private RadioGroup radioGroup;
	private ArrayList<Fragment> fs;
	private MyPagerAdapter adapter;
	private RadioButton rb0;
	private RadioButton rb1;
	private RadioButton rb2;

	private boolean isDisMiss = true;
	private MaterialDialog mMaterialDialog;
	private String apkDownloadPath; // 应用下载的地址
	public static Activity instance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_main_fragment);
		instance=this;
		update();
		setViews();
		setAdapter();
		setListener();
	}
	/**
	 * 添加监听
	 */
	@SuppressWarnings("deprecation")
	private void setListener() {
		try {
			viewPager.setOnPageChangeListener(new OnPageChangeListener() {
				public void onPageSelected(int position) {
					switch (position) {
						case 0:
							rb0.setChecked(true);
							break;
						case 1:
							rb1.setChecked(true);
							break;
						case 2:
							rb2.setChecked(true);
							break;
					}
				}
				public void onPageScrolled(int arg0, float arg1, int arg2) {

				}
				public void onPageScrollStateChanged(int arg0) {

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 设置适配器
	 */

	private void setAdapter() {
		try {
			//声明存放Fragment的List
			fs=new ArrayList<Fragment>();
			//给list添加fragment对象
			fs.add(new OrderFragment());
			fs.add(new BackGoodsFragment());
			fs.add(new UserFragment());
			//创建MyPagerAdapter 设置viewPager
			adapter=new MyPagerAdapter(getSupportFragmentManager());
			viewPager.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 组件初始化
	 */
	private void setViews() {
		viewPager=(ViewPager)findViewById(R.id.viewPager);
		radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
		rb0=(RadioButton)findViewById(R.id.radio0);
		rb1=(RadioButton)findViewById(R.id.radio1);
		rb2=(RadioButton)findViewById(R.id.radio2);
	}

	public void doClick(View view){
		switch (view.getId()) {
			case R.id.radio0:
				viewPager.setCurrentItem(0);
				break;
			case R.id.radio1:
				viewPager.setCurrentItem(1);
				break;
			case R.id.radio2:
				viewPager.setCurrentItem(2);
				break;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	class MyPagerAdapter extends FragmentPagerAdapter {

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			return fs.get(position);
		}

		@Override
		public int getCount() {
			return fs.size();
		}

	}
	@Override
	protected void onResume() {
		int id = getIntent().getIntExtra("fragid",0);
		if(id==1) {
			viewPager.setCurrentItem(0);

		}
		super.onResume();
	}

	/**
	 * 更新程序
	 */
	public void update() {
		String url = "";
		url = "http://182.92.96.58:8004/lxpub/app/version?action=getVersionInfo&project="
				+ "致惠云商";
		OkHttpUtils
				.get()
				.url(url)
				.build()
				.execute(new StringCallback() {
					@Override
					public void onError(Call call, Exception e, int id) {

					}

					@Override
					public void onResponse(String response, int id) {
						//  String body = new String(response);
						try {

							double this_version = Double.parseDouble(Tools.getVersion());

							JSONObject obj = new JSONObject(response);

							double new_version = Double.parseDouble(obj
									.getString("app_version"));

							String app_info = obj.getString("app_desc");

							String app_url = obj.getString("app_url");

							int app_necessary = obj.getInt("app_necessary");

							if (new_version > this_version) {

								updateDialog(new_version, app_info, app_url,
										app_necessary);
							} else {
//								startActivity(new Intent(SplashActivity.this,MainActivity.class));
//								finish();
							}

						} catch (JSONException e) {

							e.printStackTrace();
//							startActivity(new Intent(SplashActivity.this,MainActivity.class));
//							finish();
						}
					}
				});

	}


	private void updateDialog(double app_version, String app_info,
							  final String app_url, final int app_necessary) {

		isDisMiss = true;

		mMaterialDialog = null;
		mMaterialDialog = new MaterialDialog(MainFragmentActivity.this)
				.setTitle("发现新版本 " + app_version)
				.setMessage("更新内容:\n" + app_info + "\n\n请点击\"确定\"开始更新")
				.setPositiveButton("确定", new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						isDisMiss = false;
						mMaterialDialog.dismiss();

						apkDownloadPath = app_url;

						Toast.makeText(MainFragmentActivity.this, "正在后台进行下载，稍后会自动安装",
								Toast.LENGTH_SHORT).show();

						Intent intent = new Intent(MainFragmentActivity.this,
								DownAPKService.class);
						intent.putExtra("apk_url", apkDownloadPath);
						startService(intent);

						if (app_necessary == 0) {
//							startActivity(new Intent(SplashActivity.this,MainActivity.class));
//							finish();
						}

						// 如需使用外部浏览器下载，注释掉上边的线程，解开此句即可
						// downloadByBrowser(apkDownloadPath);

					}
				}).setCanceledOnTouchOutside(false);

		if (app_necessary == 0) {
			mMaterialDialog.setNegativeButton("取消", new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					isDisMiss = false;
					mMaterialDialog.dismiss();
//					startActivity(new Intent(SplashActivity.this,MainActivity.class));
//					finish();
				}
			});
		}

		mMaterialDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				if (isDisMiss) {
//                    if (mLocClient.isStarted()) {
//                        mLocClient.stop();
//                    }
				}

			}
		});
		mMaterialDialog.show();
	}
}
